package br.com.digitalizar.pdfpages;

import java.io.IOException;
import java.util.List;

import org.alfresco.model.ContentModel;
import org.alfresco.repo.action.executer.ActionExecuterAbstractBase;
import org.alfresco.repo.content.MimetypeMap;
import org.alfresco.service.cmr.action.Action;
import org.alfresco.service.cmr.action.ParameterDefinition;
import org.alfresco.service.cmr.dictionary.InvalidAspectException;
import org.alfresco.service.cmr.model.FileFolderService;
import org.alfresco.service.cmr.repository.ContentData;
import org.alfresco.service.cmr.repository.ContentIOException;
import org.alfresco.service.cmr.repository.ContentReader;
import org.alfresco.service.cmr.repository.InvalidNodeRefException;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeService;
import org.apache.pdfbox.pdmodel.PDDocument;

/**
 * 
 * @author Rafael de Morais
 * 
 */
public class PDFPagesExecuter extends ActionExecuterAbstractBase {

	public static final String NAME = "pdfp";

	private NodeService nodeService;
	protected FileFolderService fileFolderService;

	@Override
	protected void executeImpl(Action action, NodeRef nodeRef) {
		if (nodeService.exists(nodeRef)) {
			
			ContentData contentData = (ContentData) nodeService.getProperty(
					nodeRef, ContentModel.TYPE_CONTENT);
			
			if(contentData.getMimetype().equalsIgnoreCase(MimetypeMap.MIMETYPE_PDF)) {
				// add the aspect if it is not already present on the node
				try {
					if (!nodeService.hasAspect(nodeRef, PDFPagesAspect.ASPECT)) {
						nodeService.addAspect(nodeRef, PDFPagesAspect.ASPECT, null);
					}
				} catch (InvalidNodeRefException e) {
					// TODO ErrorHandler
					e.printStackTrace();
				} catch (InvalidAspectException e) {
					e.printStackTrace();
				}
	
				ContentReader reader = fileFolderService.getReader(nodeRef);
				try {
					PDDocument pdf = PDDocument
							.load(reader.getContentInputStream());
	
					nodeService.setProperty(nodeRef,
							PDFPagesAspect.PROP_NUMBER_OF_PAGES, pdf
									.getNumberOfPages());
	
					pdf.close();
	
				} catch (ContentIOException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
				
			}
		}
	}

	@Override
	protected void addParameterDefinitions(List<ParameterDefinition> params) {

	}

	public void setNodeService(NodeService nodeService) {
		this.nodeService = nodeService;
	}

	public void setFileFolderService(FileFolderService fileFolderService) {
		this.fileFolderService = fileFolderService;
	}
}